package com.qfedu.security;

import com.alibaba.fastjson.JSONObject;
import com.qfedu.common.R;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

public class SecurityInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            //获取处理器要执行的方法
            Method method = ((HandlerMethod) handler).getMethod();
            //获取方法上面的HasPermission注解
            HasPermission hasPermission = method.getAnnotation(HasPermission.class);
            if(hasPermission != null){
                //方法上存在权限检测的注解，那么此时就应该进行权限的校验
                String[] permissions = hasPermission.value(); //获取具备访问这个方法的权限信息
                HttpSession session = request.getSession();
                //登陆成功后，需要将当前用户的权限信息存入session中
                List<String> userPermissions = (List<String>) session.getAttribute("userPermissions");
                if (Arrays.stream(permissions).noneMatch(userPermissions::contains)) {
                    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                    PrintWriter writer = response.getWriter();
                    String json = JSONObject.toJSONString(R.error(HttpStatus.FORBIDDEN.value(), "无权访问"));
                    writer.write(json);
                    writer.flush();
                    writer.close();
                    return false;
                } else return true;
            }
            return true;
        }
        return true;
    }
}
